package com.keba.lamp.ai.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.keba.basic.utils.ArgumentAssert;
import com.keba.lamp.ai.entity.AiEndPoint;
import com.keba.lamp.ai.entity.AiModelVersion;
import com.keba.lamp.ai.service.AiEndPointService;
import com.keba.lamp.ai.service.AiModelVersionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.keba.lamp.ai.service.AiModelService;
import com.keba.basic.base.service.impl.SuperServiceImpl;
import com.keba.lamp.ai.manager.AiModelManager;
import com.keba.lamp.ai.entity.AiModel;
import com.keba.lamp.ai.vo.save.AiModelSaveVO;
import com.keba.lamp.ai.vo.update.AiModelUpdateVO;
import com.keba.lamp.ai.vo.result.AiModelResultVO;
import com.keba.lamp.ai.vo.query.AiModelPageQuery;

import java.util.Collection;

/**
 * <p>
 * 业务实现类
 * 模型
 * </p>
 *
 * @author twg
 * @date 2025-03-02 19:37:58
 * @create [2025-03-02 19:37:58] [twg] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AiModelServiceImpl extends SuperServiceImpl<AiModelManager, Long, AiModel> implements AiModelService {

    private final AiModelVersionService aiModelVersionService;

    private final AiEndPointService aiEndPointService;

    @Override
    protected <SaveVO> AiModel saveBefore(SaveVO saveVO) {
        AiModelSaveVO saveVo = (AiModelSaveVO) saveVO;
        ArgumentAssert.isFalse(superManager.exists(Wrappers.lambdaQuery(AiModel.class).eq(AiModel::getModelName, saveVo.getModelName())), "模型名称已存在");
        return super.saveBefore(saveVO);
    }

    @Override
    protected <UpdateVO> AiModel updateBefore(UpdateVO updateVO) {
        AiModelUpdateVO updateVo = (AiModelUpdateVO) updateVO;
        ArgumentAssert.isFalse(superManager.exists(Wrappers.lambdaQuery(AiModel.class).ne(AiModel::getId, updateVo.getId()).eq(AiModel::getModelName, updateVo.getModelName())), "模型名称已存在");
        return super.saveBefore(updateVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Collection<Long> idList) {
        boolean isExist = aiEndPointService.getSuperManager().exists(Wrappers.lambdaQuery(AiEndPoint.class).in(AiEndPoint::getModelId, idList));
        ArgumentAssert.isFalse(isExist, "模型正在被使用，无法删除");
        // 删除模型版本
        aiModelVersionService.getSuperManager().remove(Wrappers.lambdaQuery(AiModelVersion.class).in(AiModelVersion::getModelId, idList));
        return super.removeByIds(idList);
    }
}


